/*
 *@本js功能：实验环境
 *@本js作者：杨锡君
 *@编写时间：2017年11月7日
 */
$(function() {
    var Alert1 = new Alert();
    var Alert2 = new Alert();
    var confirm1 = new Confirm();
    var loading1 = new Loading();
    loading1.init();
    var $virtualBox = $("#virtualBox");
    var $labTextContent = $(".labTextContent");
    var $subBtn = $(".subBtn");
    var $preview = $(".preview");
    var $previewContent = $(".previewContent");
    var $redact = $(".redact");
    var $packDown = $(".packDown");
    var $packup = $(".packup");
    var $videoBtn = $(".videoBtn");
    var $noteBtn = $(".noteBtn");
    var $noteBox = $("#noteBox");
    var $downNote = $(".downNote");
    var $edits = $(".edits");
    var $mb = $(".mb");
    var $saveNote = $(".saveNote");
    var $shareDeskBtn = $(".shareDeskBtn");
    var nowCourseId,nowChapterNum;
    var roleIds = result.roleId;
	
	
	//获取文件名称
	function getFileName(path) {
		var pos1 = path.lastIndexOf('/');
		var pos2 = path.lastIndexOf('\\');
		var pos = Math.max(pos1, pos2);
		if (pos < 0) {
			return path;
		}
		else {
			return path.substring(pos + 1);
		}
	}
	
    function shareDeskModel(opt) {
        var str = "<div class=\"popups\">" +
            "<div class=\"popup_box\">" +
            "<div class=\"popup_contenthead\">分享桌面<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>" +
            "<div class=\"popup_content\">";
        var str1 = "";
        if(opt.data.teacherList.length != 0) {
            str1 += "<div class=\"teacherBox\">" +
                "<h4 class=\"fl\">教师 : </h4>";
            $.map(opt.data.teacherList, function(obj) {
                str1 += "<div class=\"fl teaOneBox\">" +
                    "<label><input type=\"checkbox\" data-stuorteaid=" + obj.stuorteaId + "  value=\"0\" class=\"teaOneCheck\" />" + obj.username + "</label>" +
                    "</div>"
            });
            str1 += "<div class=\"clear\"></div>"
                //				+"<div class=\"editDesk\">允许对方操作: <span class=\"female radioCheck\">否</span><span class=\"male radio\">是</span></div>"
                +
                "</div>";
        }
        var str2 = "";
        if(opt.data.studentList.length != 0) {
            str2 += "<div class=\"studentBox\">" +
                "<h4 class=\"fl\">学生 : </h4>" +
                "<div class=\"fl stuOneBox\">" +
                "<label><input type=\"checkbox\" name=\"controlAll\" id=\"controlAll\" class=\"allCheck\">全选</label>" +
                "</div>" +
                "<div class=\"clear\"></div>" +
                "<div class=\"stuDeskAll\">";
            $.map(opt.data.studentList, function(omg) {
                str2 += "<div class=\"fl stuOneBox\">" +
                    "<label ><input type=\"checkbox\" data-stuorteaid=" + omg.stuorteaId + "   value=\"0\" name=\"selecteds\" class=\"oneCheck\" />" + omg.username + "</label>" +
                    "</div>"
            });
            str2 += "</div>" +
                "<div class=\"clear\"></div>" +
                "<div class=\"editDesk\">允许对方操作: <span value=\"0\" class=\"females radioChecks\">否</span><span value=\"1\" class=\"males radios\">是</span><i class=\"choseStuNum fr\">共选：0 人</i></div>" +
                "</div>" +
                "<div class=\"clear\"></div>";
        }
        var str3 = "</div>" +
            "<div class=\"popup_btn\">" +
            "<a class=\"popup_confirm exportBtn hover-btn\">确定</a>" +
            "<a class=\"popup_close exportCancle hover-btn\">取消</a>" +
            "</div>" +
            "<div class=\"clear\"></div>" +
            "</div>" +
            "</div>";
        return str + str1 + str2 + str3;
    }

    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.crossOrigin = "anonymous";
        image.src = canvas.toDataURL("image/png");
        return image;
    }
    function downModel(url) {
        return '<div class="modal" style="padding-top: 10% !important;display: block;" id="download-code-modal" tabindex="-1" role="dialog" style="display: block;">' +
            '<div class="modal-dialog" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<img class="alert_img downCode" src="pc/images/ico_alertDel.png"></span>' +
            '<h4 class="modal-title">从实验环境中导出代码</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '将需要的代码文件放入到“/data”目录，点击下载会把该目录打包下载。' +
            '</div>' +
            '<div class="modal-footer">' +
            '<a href="'+ url +'" class="publicBtn confirm downCode" download>下载</a>' +
            '<button class="shearClose publicBtn downCode" type="button" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
    }
    function shearModel() {
        return '<div class="modal" id="clipboard-modal" tabindex="-1" role="dialog" style="display: block;">' +
            '<div class="modal-dialog" role="document">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<img class="alert_img shearClose shearCloses" src="pc/images/ico_alertDel.png"></span>' +
            '<h4 class="modal-title">剪切板</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '<div>' +
            '<strong>复制外部内容到实验环境内：</strong>粘贴内容到下方输入框，点击‘保存’在实验环境中粘贴。' +
            '</div>' +
            '<textarea maxlength="20000" class="maxLimit" id="praseArea"></textarea>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button class="  clipboard-copy-btn publicBtn" type="button">保存</button>' +
            '<button class="  shearClose shearCloses publicBtn" type="button" data-dismiss="modal">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
    }
    function saveImage() {
        return '<div class="popup" style="display: block">' +
            '<div class="popup_box">' +
            '<div class="popup_contenthead">保存镜像<img class="popup_img imageClose" src="pc/images/ico_alertDel.png"></div>' +
            '<div class="popup_content">' +
            '<div class="inputRight"><label for="imgName">镜像名称: </label>' +
            '<input type="text" class="publicText" id="imgName">' +
            '</div>' +
            '</div>' +
            '<div class="popup_btn">' +
            '<a  class="popup_confirm exportBtn saveImgTrue publicBtn hover-btn">确定</a>' +
            '<a class="popup_close exportCancle imageClose ">取消</a>' +
            '</div>' +
            '<div class="clear"></div>' +
            '</div>' +
            '</div>';
    }
		//上传镜像盒内容
		function upLoadbox(){
			return '<div class="popup" id="upload-modal" tabindex="-1" role="dialog"  style="display: block;z-index:100;height:auto">' +
	            '<div class="popup_box">' +			
	            '<div class="popup_contenthead">上传文件<img class="popup_img imageClose" src="pc/images/ico_alertDel.png"></div>' +
	            '<div class="popup_content">' +				
	            '<div class="inputRight" style="margin-top:10px">'+
				'<label for="uploadfile" class="uploadlabel">上传文件</label>' +
				'<div class="filename"></div>' +
				'<h5 style="color:#a3010e;">*上传至当前虚拟机root文件夹</h5>'+
	            '<input type="file" class="publicText" id="uploadfile" name="uploadfile" style="display:none">' +
	            '</div>' +
	            '</div>' +
	            '<div class="popup_btn">' +
	            '<a  class="popup_confirm exportBtn upLoadTrue publicBtn hover-btn">确定</a>' +
	            '<a class="popup_close exportCancle imageClose ">取消</a>' +
	            '</div>' +
	            '<div class="clear"></div>' +
	            '</div>' +
	            '</div>';	
		}
    var lab = {
        report:'',
        note:'',
        init: function() {
            var self = this;
            var environmentParam = result;
            self.nowCourseId = environmentParam.courseId;
            self.nowChapterNum = environmentParam.chapterNum;
            // startWebSocket(environmentParam.courseId,environmentParam.chapterId);
            self.bindEvent(environmentParam.courseId,environmentParam.chapterNum,environmentParam.chapterId);
            // 权限
            if(roleIds != 1){
                $(".title>div").eq(1).remove();
                $(".title>div").eq(1).remove();
                $noteBtn.remove();
            }else{
                $(".saveImg").remove();
            }

        },
        bindEvent: function(courseId,chapterNum,chapterId) {
            var self = this;
            self.getLabTime(chapterId);
            // 工具栏
            $(".closeSide").off("click").click(function () {
                if($(this).attr("data-value") == 0){
                    $(this).attr("data-value",1);
                    $(".navSideBar").animate({
                        "right":"-120px"
                    },300);
                }else{
                    $(this).attr("data-value",0);
                    $(".navSideBar").animate({
                        "right":"0"
                    },300);
                }
            });
            $(".edit").mousedown(function (e) {
                var event = e || window.event;
                var str = event.target;
                self.report = str;
            });
            $(".edits").mousedown(function (e) {
                var event = e || window.event;
                var str = event.target;
                self.note = str;
            });
            $(".closeSftp").off("click").click(function () {
                $(".sftpBox").hide();
            });
            // 获取课程ID章节NUM
            self.titleTap();
            self.getData(courseId,chapterNum,chapterId);
            //提交实验报告
            $(".submit").off("click").click(function() {
                self.reportSubmit(courseId,chapterNum,chapterId);
            });
            //保存实验报告
            $(".saveBook").off("click").click(function() {
                self.reportSave(courseId,chapterNum);
            });
            $noteBtn.off("click").click(function() {
                self.noteEvent(courseId,chapterNum);
            });
            //刷新
            $(".relink").off("click").click(function () {
                // 虚机资源获取
                var jsons = {"courseId":courseId,"chapterId":chapterId};
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "desktop/query",
                    data:jsons,
                    async: true,
                    success: function (msg) {
                        loading1.hide();
                        if(msg.code == "200"){
                            var str = '';
                            var str1 = '';
                            $(".nav").remove();
                            $(".virMBox").remove();
                            if(msg.data.cluster == true){
                                setTimeout(function () {
                                    str += "<li data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点(当前)</li>";
                                    str += "<li data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                    str += "<li data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                    $("#virtualBox").append("<iframe name='virMBoxes' data-value='1' data-containerid="+ msg.data.masterContainerId  +" class=\"virMBox\" src="+msg.data.masterDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");
                                    $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.firstSlaveContainerId +" class=\"virMBox\" src="+msg.data.firstSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                    $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.secondSlaveContainerId +" class=\"virMBox\" src="+msg.data.secondSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                    // $(".configBox>ul").html(str);
                                    str1 += "<li type='1' class='nav mainVir' data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点</li>";
                                    str1 += "<li type='2' class='nav subVir' data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                    str1 += "<li type='2' class='nav thVir' data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                    $(".virAfter").after(str1);
                                },1000);

                            }else{
                                setTimeout(function () {
                                    $(".configBtn").remove();
                                    // str += "<li data-value='1' data-url='"+ msg.data.desktopUrl +"'  data-containerid="+ msg.data.containerId +">单节点(当前)</li>";
                                    $("#virtualBox").append("<iframe  name='virMBoxes' data-value='1' data-containerid="+ msg.data.containerId +" class=\"virMBox\" src="+msg.data.desktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");

                                },1000);
                            }
                            setTimeout(function () {
                                self.somethingEvent(courseId,chapterId,chapterNum);
                                $(".mainVir").css({"background":'url(pc/images/ico_labMPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                $(".mainVir").off("click").click(function () {
                                    $(".nav").attr("style",'');
                                    $(".nav").attr("data-value",'0');
                                    $(this).css({"background":'url(pc/images/ico_labMPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                    $(this).attr("data-value","1");
                                    $(".virMBox").attr("data-value","0").hide();
                                    $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                });
                                $(".subVir").off("click").click(function () {
                                    $(".nav").attr("style",'');
                                    $(".nav").attr("data-value",'0');
                                    $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                    $(this).attr("data-value","1");
                                    $(".virMBox").attr("data-value","0").hide();
                                    $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                });
                                $(".thVir").off("click").click(function () {
                                    $(".nav").attr("style",'');
                                    $(".nav").attr("data-value",'0');
                                    $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                    $(this).attr("data-value","1");
                                    $(".virMBox").attr("data-value","0").hide();
                                    $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                });
                            },1000);

                            // 实验环境Loading
                            setTimeout(function () {
                                $("#virtualBox").append("<div style='width:100%;height:100%;background:#666666;position:absolute;left:0;top:0;' class='loadingBg'><img style='transform:scale(0.7);position:absolute;left:50%;top:50%;margin-left:-200px;margin-top:-75px;' class='loadings' src='pc/images/labLoadings.gif'></div>");
                                $(".virMBox[data-value=1]").load(function () {
                                    $(".loadingBg").remove();
                                });
                            },1000);


                            self.screenShoot();
                            $(".shareDeskCloseBtn").off("click").click(function () {
                                var serverid = $(".virMBox[data-value=1]").attr("data-containerid");
                                if(serverid == undefined){
                                    Alert1.content = "当前无法关闭分享";
                                    Alert1.init();
                                    Alert1.show();
                                }else{
                                    var json = {"containerId":serverid};
                                    $.ajax({
                                        type: "get",
                                        url: "desktop/unshare",
                                        data:json,
                                        async: true,
                                        success: function(msg) {
                                            if(msg.code == "200"){
                                                Alert1.content = "关闭分享成功";
                                                Alert1.success = function () {
                                                };
                                                Alert1.init();
                                                Alert1.show();
                                            }else{
                                                Alert1.content = msg.message;
                                                Alert1.init();
                                                Alert1.show();
                                            }
                                        }
                                    });
                                }

                            });
                        }else{
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                        }
                    }
                });
            });

            self.editAndShow();
            self.packupEvent();
            self.layout();
            // 配置
            $(".configBtn").off("click").click(function() {
                if($(this).attr("data-value") == 0){
                    $(".configBox").show();
                    $(this).attr("data-value",1);
                }else{
                    $(".configBox").hide();
                    $(this).attr("data-value",0);
                }
            });
        },
        somethingEvent:function (courseId,chapterId,chapterNum) {
            var self = this;
            // SFTP
            $(".sftp").off("click").click(function () {
                $(".sftpBox").show();
                // 获取sftp地址和端口
                $.ajax({
                    type: "get",
                    url: "desktop/ftp",
                    data: {"containerId":Number($(".virMBox[data-value=1]").attr("data-containerid"))},
                    async: true,
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (msg) {
                        if (msg.code == "200") {
                            var arr = msg.data.ftp.split(":");
                            $(".blueHtml").html(arr[0]);
                            $(".blueHtml2").html(arr[1]);
                        }else{
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                            return false;
                        }
                    }
                });
            });
            $shareDeskBtn.off("click").click(function() {
                var jsonStr = {
                    "chapterId":chapterId,
                    "courseId":courseId
                };
                loading1.show();
                $.ajax({
                    type: "get",
                    url: "desktop/onlineUser",
                    async: true,
                    data: jsonStr,
                    success: function(msg) {
                        loading1.hide();
                        if(msg.code == "200") {
                            if(msg.data.teacherList.length == 0&& msg.data.studentList.length == 0){
                                Alert1.content = "当前没有其他在线人员";
                                Alert1.init();
                                Alert1.show();
                            }else{
                                $mb.show();
                                $("body").append(shareDeskModel(msg));
                                self.popupEvent(courseId,chapterNum,chapterId,msg);
                            }

                        } else {
                            Alert1.content = msg.message;
                            Alert1.init();
                            Alert1.show();
                        }

                    }
                });
            });
            //保存镜像
            $(".saveImg").off("click").click(function () {
                var str = saveImage();
                $(".masking").show();
                $("body").append(str);
                $(".imageClose").off("click").click(function () {
                    $(".masking").hide();
                    $(".popup").remove();
                });
                $(".saveImgTrue").off("click").click(function () {
                    var json = JSON.stringify({"imageName":$("#imgName").val(),"containerId":Number($(".virMBox[data-value=1]").attr("data-containerid"))});
                    if($("#imgName").val() == ""){
                        Alert1.content = "请输入镜像名称";
                        Alert1.init();
                        Alert1.show();
                    }else{
                        loading1.show();
                        $.ajax({
                            type: "post",
                            url: "image/create",
                            dataType:'json',
                            contentType:'application/json',
                            data: json,
                            async: true,
                            success: function (msg) {
                                loading1.hide();
                                if(msg.code == 200) {
                                    Alert1.content = "保存镜像成功";
                                    $(".masking").hide();
                                    $(".popup").remove();
                                    var url = $(".virMBox[data-value=1]").attr("src");
                                    $(".virMBox[data-value=1]").attr("src", url);
                                    Alert1.init();
                                    Alert1.show();
                                }else{
                                    Alert1.content = msg.message;
                                    Alert1.init();
                                    Alert1.show();
                                    return false;
                                }
                            }
                        });
                    }
                });
            });
			//'<h5 style="color:#a3010e;">*上传至当前虚拟机root文件夹</h5>'+事件
			$(".upload").off("click").click(function(){				
					//加载弹框
				$("body").append(upLoadbox());
				//显示背景，可遮挡其他功能键，防止点击
				$(".abs_bg").show();				
				//取消按钮事件
				$("#upload-modal .imageClose").off("click").click(function(){
					$("#upload-modal").remove();
					$(".abs_bg").hide();
				});
				//选中文件后显示文件名称
				$("#uploadfile").change(function(){
					 var str = $(this).val();
        			 var fileName = getFileName(str);					 
					 $(".filename").html(fileName);
				});
				//上传按钮事件
				$("#upload-modal .upLoadTrue").off("click").click(function(){	
					
					var uploadfile=	document.getElementById("uploadfile");
					var uploadfilename=	uploadfile.value;	
					if(uploadfilename=="")
					{
						Alert1.content = "请选择要上传的文件！";
						Alert1.init();
						Alert1.show();
					}else	if(((uploadfile.files[0].size).toFixed(2))>=(250*1024*1024))
					{
						Alert1.content = "文件大小不能超过250M！";
						Alert1.init();
						Alert1.show();
					}else
					{
						loading1.show();
						//获取当前活动的节点ID
						var containerId=$(".virMBox:visible").attr("data-containerid");
						var formData = new FormData();
						formData.append("file", document.getElementById("uploadfile").files[0]); 
						loading1.show();
						$("#upload-modal").remove();
						$(".abs_bg").hide();				
						$.ajax({
							url: "desktop/"+containerId+"/ftp",
							type: "POST",
							data: formData,
							/**
							*必须false才会自动加上正确的Content-Type
							*/
							contentType: false,
							/**
							* 必须false才会避开jQuery对 formdata 的默认处理
							* XMLHttpRequest会对 formdata 进行正确的处理
							*/
							processData: false,
							success: function (data) {
								console.log(data)				
								if (data.code == "200") {
									Alert1.content = "文件上传成功。";
									Alert1.init();
									Alert1.show();					
								}else
								{
									Alert1.content = "上传失败！";
									Alert1.init();
									Alert1.show();
								}
								loading1.hide();				
							},
							error: function () {
								Alert1.content = "上传失败！";
								Alert1.init();
								Alert1.show();
								loading1.hide();
							}
						});						
					}				
					
				});
			});
            // 下载代码
            $(".labDownLoadBtn").off("click").click(function () {
                var str = 'desktop/download?courseId=' + courseId + '&chapterId=' + chapterId;
                var string = downModel(str);
                $("body").append(string);
                $(".modal .downCode").off("click").click(function () {
                    $("#download-code-modal").remove();
                });
            });
            // 剪切板
            $(".shearBoardBtn").off("click").click(function () {
                var string = shearModel();
                $("#clipboard-modal").remove();
                $("body").append(string);
                maxLengthLimit.init("maxLimit");
                $(".shearCloses").off("click").click(function () {
                    $("#clipboard-modal").remove();
                });
                $(".clipboard-copy-btn").off("click").click(function () {
                    loading1.show();
                    var jsonStr = JSON.stringify({"content":$("#praseArea").val(),"containerId":Number($(".virMBox[data-value=1]").attr("data-containerid"))});
                    $.ajax({
                        type: "post",
                        url: "desktop/clipboard",
                        data:jsonStr,
                        async: true,
                        dataType:'json',
                        contentType:'application/json',
                        success: function (msg) {
                            loading1.hide();
                            if (msg.code == "200") {
                                $("#clipboard-modal").remove();
                                Alert1.content = "保存成功，请在实验环境中粘贴内容";
                                Alert1.init();
                                Alert1.show();
                            }else{
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    });
                });
            });
            //替换虚机
            $(".exchangeBtn").off("click").click(function () {
                confirm1.content = "确定替换虚拟机？";
                confirm1.success = function () {
                    loading1.show();
                    $.ajax({
                        type: "get",
                        url: "desktop/replace",
                        data:{
                            "courseId":courseId,
                            "chapterId":chapterId
                        },
                        async: true,
                        success: function (msg) {
                            loading1.hide();
                            $(".virMBox").remove();
                            if(msg.code == "200"){
                                var str = '';
                                var str1 = '';
                                $(".nav").remove();
                                if(msg.data.cluster == true){
                                    setTimeout(function () {
                                        str += "<li data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点(当前)</li>";
                                        str += "<li data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                        str += "<li data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                        $("#virtualBox").append("<iframe name='virMBoxes' data-value='1' data-containerid="+ msg.data.masterContainerId  +" class=\"virMBox\" src="+msg.data.masterDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");
                                        $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.firstSlaveContainerId +" class=\"virMBox\" src="+msg.data.firstSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                        $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.secondSlaveContainerId +" class=\"virMBox\" src="+msg.data.secondSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                        // $(".configBox>ul").html(str);
                                        str1 += "<li type='1' class='nav mainVir' data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点</li>";
                                        str1 += "<li type='2' class='nav subVir' data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                        str1 += "<li type='2' class='nav thVir' data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                        $(".virAfter").after(str1);
                                    },1000);

                                }else{
                                    setTimeout(function () {
                                        $(".configBtn").remove();
                                        // str += "<li data-value='1' data-url='"+ msg.data.desktopUrl +"'  data-containerid="+ msg.data.containerId +">单节点(当前)</li>";
                                        $("#virtualBox").append("<iframe  name='virMBoxes' data-value='1' data-containerid="+ msg.data.containerId +" class=\"virMBox\" src="+msg.data.desktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");

                                    },1000);
                                }

                               setTimeout(function () {
                                   $(".mainVir").css({"background":"url(pc/images/ico_labMPC2.png) no-repeat left 6px center","color":'#0fcc8c'});
                                   $(".mainVir").off("click").click(function () {
                                       $(".nav").attr("style",'');
                                       $(".nav").attr("data-value",'0');
                                       $(this).css({"background":'url(pc/images/ico_labMPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                       $(this).attr("data-value","1");
                                       $(".virMBox").attr("data-value","0").hide();
                                       $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                   });
                                   $(".subVir").off("click").click(function () {
                                       $(".nav").attr("style",'');
                                       $(".nav").attr("data-value",'0');
                                       $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                       $(this).attr("data-value","1");
                                       $(".virMBox").attr("data-value","0").hide();
                                       $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                   });
                                   $(".thVir").off("click").click(function () {
                                       $(".nav").attr("style",'');
                                       $(".nav").attr("data-value",'0');
                                       $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                       $(this).attr("data-value","1");
                                       $(".virMBox").attr("data-value","0").hide();
                                       $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                                   });
                               },1000);

                                // 实验环境Loading
                                setTimeout(function () {
                                    $("#virtualBox").append("<div style='width:100%;height:100%;background:#666666;position:absolute;left:0;top:0;' class='loadingBg'><img style='transform:scale(0.7);position:absolute;left:50%;top:50%;margin-left:-200px;margin-top:-75px;' class='loadings' src='pc/images/labLoadings.gif'></div>");
                                    $(".virMBox[data-value=1]").load(function () {
                                        $(".loadingBg").remove();
                                    });
                                },1000);


                                $(".shareDeskCloseBtn").off("click").click(function () {
                                    var serverid = $(".virMBox[data-value=1]").attr("data-containerid");
                                    if(serverid == undefined){
                                        Alert1.content = "当前无法关闭分享";
                                        Alert1.init();
                                        Alert1.show();
                                    }else{
                                        var json = {"containerId":serverid};
                                        $.ajax({
                                            type: "get",
                                            url: "desktop/unshare",
                                            data:json,
                                            async: true,
                                            success: function(msg) {
                                                if(msg.code == "200"){
                                                    Alert1.content = "关闭分享成功";
                                                    Alert1.success = function () {
                                                    };
                                                    Alert1.init();
                                                    Alert1.show();
                                                }else{
                                                    Alert1.content = msg.message;
                                                    Alert1.init();
                                                    Alert1.show();
                                                }
                                            }
                                        });
                                    }

                                });
                            }else if(msg.code == 500503){
                                $(".navSideBar").remove();
                                $("#virtualBox").css("background","url(pc/images/bg_labNoneVir.png) no-repeat center center");
                            } else{
                                Alert1.content = msg.message;
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    });
                };
                confirm1.init();
                confirm1.show();
            });

        },
        getLabTime:function (chapterId) {
            // 获取试验时间
            if(result.roleId == 1){
                $.ajax({
                    type: "get",
                    url: "statistic/query?chapterId="+chapterId,
                    async: true,
                    success: function(msg) {
                        if(msg.code == "200"){
                            var hour = Math.floor(msg.data.experimentTime/3600);
                            var min = Math.floor((msg.data.experimentTime - hour*3600)/60);
                            if(hour<10){
                                hour = "0"+hour;
                            }
                            if(min<10){
                                min = "0"+min;
                            }
                            $(".labNowTime").html(hour+":"+min);
                            var h = Number(hour);
                            var m = Number(min);
                            setInterval(function () {
                                m = Number(m);
                                h = Number(h);
                                m++;
                                if(m >= 60){
                                    h++;
                                    m = 0;
                                }
                                if(h < 10){
                                    h = "0" + h;
                                }
                                if(m < 10){
                                    m = "0" + m;
                                }
                                $(".labNowTime").html(h+":"+m);
                            },60000);
                        }
                    }
                });
            }
            if(result.roleId == 2){
                var h = 0;
                var m = 0;
                setInterval(function () {
                    m = Number(m);
                    h = Number(h);
                    m++;
                    if(m >= 60){
                        h++;
                        m = 0;
                    }
                    if(h < 10){
                        h = "0" + h;
                    }
                    if(m < 10){
                        m = "0" + m;
                    }
                    $(".labNowTime").html(h+":"+m);
                },60000);
            }
        },
        popupEvent: function(courseId,chapterNum,chapterId,msg) {
            //			分享相关事件
            //取消和X事件
            $(".popup_img").off("click").on("click", function() {
                $(".popups").remove();
                $mb.hide();
            });
            $(".exportCancle").off("click").on("click", function() {
                $(".popups").remove();
                $mb.hide();
            });
            //			//教师权限选择
            //			$(".male").off("click").on("click", function() {
            //				$(this).removeClass("radio").addClass("radioCheck");
            //				$(".female").removeClass("radioCheck").addClass("radio");
            //			});
            //			$(".female").off("click").on("click", function() {
            //				$(this).removeClass("radio").addClass("radioCheck");
            //				$(".male").removeClass("radioCheck").addClass("radio");
            //			});
            //学生权限选择
            $(".males").off("click").on("click", function() {
                $(this).removeClass("radios").addClass("radioChecks");
                $(".females").removeClass("radioChecks").addClass("radios");
            });
            $(".females").off("click").on("click", function() {
                $(this).removeClass("radios").addClass("radioChecks");
                $(".males").removeClass("radioChecks").addClass("radios");
            });
            //全选 单选
            allCheck.init("controlAll", "oneCheck");
            $("#controlAll").off("click").click(function() {

                var checklist = document.getElementsByName("selecteds");
                if(document.getElementById("controlAll").checked) {
                    for(var i = 0; i < checklist.length; i++) {
                        checklist[i].checked = 1;
                        checklist[i].value = "1";
                    }

                } else {
                    for(var j = 0; j < checklist.length; j++) {
                        checklist[j].checked = 0;
                        checklist[j].value = "0";
                    }
                }
                $(".choseStuNum").html("共选：" + $(".oneCheck[value=1]").length + "人");

            });
            $(".oneCheck").off("change").change(function() {

                if($(this).val() == "0") {
                    $(this).val("1");

                } else {
                    $(this).val("0");

                }
                $(".choseStuNum").html("共选：" + $(".oneCheck[value=1]").length + "人");
            });
            $(".teaOneCheck").change(function() {

                if($(this).val() == "0") {
                    $(this).val("1");
                } else {
                    $(this).val("0");
                }
            });
            //			确认分享事件
            $(".exportBtn").off("click").click(function() {
                var arr = [];
                if($(".teaOneCheck[value=1]").length != 0) {
                    $.each($(".teaOneCheck[value=1]"), function(opt) {
                        arr.push($(this).attr("data-stuorteaid"));
                    });
                }
                if($(".oneCheck[value=1]").length != 0) {
                    $.each($(".oneCheck[value=1]"), function(opt) {
                        arr.push($(this).attr("data-stuorteaid"));
                    });
                }
                if(arr.length == 0) {
                    Alert2.content = "请选择分享对象";
                    Alert2.success = function () {
                        $mb.show();
                        if($(".popups").length == 0){
                            $("body").append(shareDeskModel(msg));
                        }
                    };
                    Alert2.init();
                    Alert2.show();
                    return false;
                } else {
                    var isControllable = 1;
                    if($(".radioChecks").length == 0) {
                        isControllable = 1
                    } else {
                        isControllable = Number($(".radioChecks").attr("value"));
                    }
                    var serverid = $(".virMBox[data-value=1]").attr("data-containerid");
                    var jsonStr = JSON.stringify({"containerId":serverid,"stuorteaIdList":arr,"controllable":isControllable});
                    confirm1.content = "确认分享桌面吗？";
                    confirm1.success = function() {
                        loading1.show();
                        $.ajax({
                            type: "post",
                            url:'desktop/share',
                            async: true,
                            contentType:"application/json;charset=utf-8",
                            data: jsonStr,
                            success: function(msg) {
                                loading1.hide();
                                if(msg.code == "200") {
                                    Alert1.content = "分享桌面成功";
                                    Alert1.success = function() {
                                        $(".popups").remove();
                                        $mb.hide();
                                    };
                                    Alert1.init();
                                    Alert1.show();
                                } else {
                                    Alert1.content = msg.message;
                                    Alert1.init();
                                    Alert1.show();
                                }
                            }
                        });
                    };
                    confirm1.init();
                    confirm1.show();
                }

            });
        },
        noteEvent: function(courseId,chapterNum) {
            var self = this;
            self.noteMove();
            //				实验笔记相关事件
            if($noteBtn.html() == "笔记") {
                $noteBtn.html("关闭笔记");
                $noteBox.show();

            } else {
                $noteBtn.html("笔记");
                $noteBox.hide();
            }
            $downNote.off("click").click(function() {
                $edits.wordExport()
            });
            $saveNote.off("click").click(function() {
                var jsonStr = JSON.stringify({
                    "chapterNum": chapterNum,
                    "courseId": courseId,
                    "noteStr": $edits.html()
                });
                loading1.show();
                $.ajax({
                    type: "post",
                    url: "uploadNote",
                    async: true,
                    data:{
                        "jsonStr":jsonStr
                    },
                    success: function(msg) {
                        loading1.hide();
                        msg = JSON.parse(msg);
                        if(msg.result == "success") {
                            Alert1.content = "实验笔记保存成功";
                            Alert1.init();
                            Alert1.show();
                        }else{
                            Alert1.content = "实验笔记保存失败";
                            Alert1.init();
                            Alert1.show();
                        }
                    }
                });
            });
            $(".packupNote").off("click").click(function() {
                $noteBtn.html("笔记");
                $noteBox.hide();
            });
        },
        noteMove:function () {
            var div1 = document.getElementById("noteBox");
            var div2 = document.getElementById("titles");
            div2.onmousedown = function(e){
                var e = e || window.event;
                var x = e.clientX - div1.offsetLeft;
                var y = e.clientY - div1.offsetTop;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
                document.onmousemove = function(e){
                    var e = e || window.event;
                    if(e.preventDefault){
                        e.preventDefault();
                    }
                    else{
                        e.returnValue = false;
                    }
                    var wid = e.clientX - x ;
                    var hei = e.clientY - y ;
                    if(wid < 0){
                        wid = 0 ;
                    }
                    if(wid > getClientWidth() - div1.offsetWidth){
                        wid = getClientWidth() - div1.offsetWidth;
                    }
                    if(hei < 0){
                        hei = 0 ;
                    }
                    if(hei > getClientHeight() - div1.offsetHeight){
                        hei = getClientHeight() - div1.offsetHeight;
                    }
                    div1.style.left = wid + "px";
                    div1.style.top = hei + "px";
                }
            };
            document.onmouseup = function(e){
                var e = e || event;
                document.onmousemove = null;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
            };
        },
        editAndShow: function() {
            //				编辑与与预览
            $redact.click(function() {
                $(".trumbowyg-box").show();
                $previewContent.hide();
                $redact.removeClass("span2").addClass("span1");
                $preview.removeClass("span1").addClass("span2");
                $subBtn.show();
            });
            $preview.click(function() {
                $subBtn.hide();
                $preview.removeClass("span2").addClass("span1");
                $redact.removeClass("span1").addClass("span2");
                $(".trumbowyg-box").hide();
                $previewContent.show().empty().append($(".edit").html());
            });
        },
        packupEvent: function() {
            var self = this;
            //				收起展开等事件
            if($(".virEnvirmentBox").length != 0){
                var timers = setInterval(function() {
                    $(".virEnvirmentBox").width((1024 / 768) * ($(window).height() - 38));
                    $("#box").width($(window).width() - $(".virEnvirmentBox").width() - 1);
                }, 50);
                if(window.screen.width<1280){
                    clearInterval(timers);
                    $(".virEnvirmentBox").css("width","100%");
                    $("#box").hide();
                    $packDown.show();
                }
            }
            $packup.off("click").click(function() {
                $("#box").hide();
                // $(".looktgsub").show();
                // $(".looktgMain").hide();
                $packDown.show();
                clearInterval(timers);
                $(".virEnvirmentBox").css("width","100%");
            });
            $(".packups").off("click").click(function() {
                $("#box").css({"width":'706px',"position":"absolute","top":"50px","left":"50px","z-index":"100","height":"60%"});
                // $(".looktgsub").show();
                // $(".looktgMain").hide();
                clearInterval(timers);
                self.labMove();
                $(".virEnvirmentBox").css("width","100%");
                $(".packdowns").show();
                $(".contentSection").height(528);
                $(".packups").hide();
                $(".reportShow").height(464);
                if($(".span1").html()=="编辑"){
                    $(".trumbowyg-box").show();
                    $previewContent.hide();
                    $subBtn.show();
                }else{
                    $(".trumbowyg-box").hide();
                    $previewContent.show();
                    $subBtn.hide();
                }
            });
            $(".packdowns").off("click").click(function() {
                $("#box").attr("style","width: 706px;");
                // $(".looktgsub").hide();
                // $(".looktgMain").show();
                $(".packdowns").hide();
                $(".contentSection").height($(window).height() - 38);
                $(".packups").show();
                $(".reportShow").height($(window).height()-120);
                timers = setInterval(function() {
                    $(".virEnvirmentBox").width((1024 / 768) * ($(window).height() - 38));
                    $("#box").width($(window).width() - $(".virEnvirmentBox").width() - 1);
                }, 50);
            });
            $packDown.off("click").click(function() {
                $("#box").show();
                $("#box").css({"width":'706px',"position":"absolute","top":"50px","left":"50px","z-index":"100","height":"60%"});
                clearInterval(timers);
                self.labMove();
                $(".virEnvirmentBox").css("width","100%");
                $packDown.hide();
                $(".packups").hide();
                $(".packdowns").show();
                if(window.screen.width<1280){
                    $(".packdowns").hide();
                }
                // timers = setInterval(function() {
                //     $(".virEnvirmentBox").width((1024 / 768) * ($(window).height() - 38));
                //     $("#box").width($(window).width() - $(".virEnvirmentBox").width() - 1);
                // }, 50);
            });

        },
        labMove:function () {
            var div1 = document.getElementById("box");
            var div2 = document.getElementById("title");
            div2.onmousedown = function(e){
                var e = e || window.event;
                var x = e.clientX - div1.offsetLeft;
                var y = e.clientY - div1.offsetTop;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
                document.onmousemove = function(e){
                    var e = e || window.event;
                    if(e.preventDefault){
                        e.preventDefault();
                    }
                    else{
                        e.returnValue = false;
                    }
                    var wid = e.clientX - x ;
                    var hei = e.clientY - y ;
                    if(wid < 0){
                        wid = 0 ;
                    }
                    if(wid > getClientWidth() - div1.offsetWidth){
                        wid = getClientWidth() - div1.offsetWidth;
                    }
                    if(hei < 0){
                        hei = 0 ;
                    }
                    if(hei > getClientHeight() - div1.offsetHeight){
                        hei = getClientHeight() - div1.offsetHeight;
                    }
                    div1.style.left = wid + "px";
                    div1.style.top = hei + "px";
                }
            };
            document.onmouseup = function(e){
                var e = e || event;
                document.onmousemove = null;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
            };
        },
        videoShow: function(url) {
            //				视频
            var self = this;
            $videoBtn.off("click").click(function() {
                if(url == 0){
                    Alert1.content = "当前没有视频资源";
                    Alert1.init();
                    Alert1.show();
                }else{
                    if($videoBtn.html() == "视频") {
                        $videoBtn.html("关闭视频");
                        $("body").append("<div id='videoSec'><header id='videoTitle'>视频<img class=\"closeVideoBtns\" src=\"pc/images/ico_alertDel.png\"></header><video id='videoBox' autoplay controls src='" + url + "'></video></div>");
                        $("#videoBox").css("height",$("#videoSec").height()-40+"px");
                        self.videoMove("videoBox");
                        $(".closeVideoBtns").off("click").click(function() {
                            $videoBtn.html("视频");
                            $("#videoSec").remove();
                        });
                    } else {
                        $videoBtn.html("视频");
                        $("#videoSec").remove();
                    }
                }

            });
        },
        videoMove: function() {
            var div1 = document.getElementById("videoSec");
            var div2 = document.getElementById("videoTitle");
            div2.onmousedown = function(e){
                var e = e || window.event;
                var x = e.clientX - div1.offsetLeft;
                var y = e.clientY - div1.offsetTop;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
                document.onmousemove = function(e){
                    var e = e || window.event;
                    if(e.preventDefault){
                        e.preventDefault();
                    }
                    else{
                        e.returnValue = false;
                    }
                    var wid = e.clientX - x ;
                    var hei = e.clientY - y ;
                    // if(wid < 0){
                    //     wid = 0 ;
                    // }
                    // if(wid > getClientWidth() - div1.offsetWidth){
                    //     wid = getClientWidth() - div1.offsetWidth;
                    // }
                    // if(hei < 0){
                    //     hei = 0 ;
                    // }
                    // if(hei > getClientHeight() - div1.offsetHeight){
                    //     hei = getClientHeight() - div1.offsetHeight;
                    // }
                    div1.style.left = wid + "px";
                    div1.style.top = hei + "px";
                }
            };
            document.onmouseup = function(e){
                var e = e || event;
                document.onmousemove = null;
                if(e.preventDefault){
                    e.preventDefault();
                }
                else{
                    e.returnValue = false;
                }
            };
        },
        reportSave: function(courseId,chapterNum) {
            //提报告

            if($(".edit").html() == "") {
                Alert1.content = "实验报告不能为空";
                Alert1.init();
                Alert1.show();
            } else {
                var confirm1 = new Confirm();
                confirm1.content = "确定保存实验报告?";
                confirm1.init();
                confirm1.success = function() {
                    var htm = escape($(".edit").html());
                    var jsonStr = {
                        "courseId": courseId,
                        "chapterNum": chapterNum,
                        // "stuorteaId": result.stuorteaId,
                        "taskAddress": htm
                    };
                    loading1.show();
                    jsonStr = JSON.stringify(jsonStr);
                    $.ajax({
                        type: "post",
                        url: "saveStuTestPractice",
                        async: true,
                        data: {
                            "jsonStr": jsonStr
                        },
                        success: function(msg) {
                            loading1.hide();
                            msg = JSON.parse(msg);
                            if(msg.result == "success") {
                                Alert1.content = "实验报告保存成功";
                                Alert1.init();
                                Alert1.show();
                            }else{
                                if(msg.failMsg!=undefined){
                                    if(msg.failMsg != ""){
                                        Alert1.content = msg.failMsg;
                                    }else{
                                        Alert1.content = "实验报告保存失败";
                                    }
                                    Alert1.init();
                                    Alert1.show();
                                }else{
                                    Alert1.content = "实验报告保存失败";
                                    Alert1.init();
                                    Alert1.show();
                                }
                            }
                        }
                    });

                };
                confirm1.show();

            }

        },
        reportSubmit: function(courseId,chapterNum,chapterId) {
            //提报告

            if($(".edit").html() == "") {
                Alert1.content = "实验报告不能为空";
                Alert1.init();
                Alert1.show();
            } else {
                var confirm1 = new Confirm();
                confirm1.content = "确定提交实验报告?";
                confirm1.init();
                confirm1.success = function() {
                    var htm = escape($(".edit").html());
                    var jsonStr = {
                        "courseId": courseId,
                        "chapterNum": chapterNum,
                        "mapList":'',
                        "chapterId":chapterId,
                        "optionSource":0,
                        "judgeSource":0,
                        "manyOptionSource":0,
                        "taskType": 2,
                        "htmlStr": htm,
                        "cssStr":''
                    };
                    loading1.show();
                    jsonStr = JSON.stringify(jsonStr);
                    $.ajax({
                        type: "post",
                        url: "uploadTest",
                        async: true,
                        data: {
                            "jsonStr": jsonStr
                        },
                        success: function(msg) {
                            loading1.hide();
                            msg = JSON.parse(msg);
                            if(msg.result == "success") {
                                var jsonStrs = {
                                    "courseId": courseId,
                                    "chapterNum": chapterNum,
                                    // "stuorteaId": result.stuorteaId,
                                    "taskAddress": htm
                                };
                                jsonStrs = JSON.stringify(jsonStrs);
                                loading1.show();
                                $.ajax({
                                    type: "post",
                                    url: "saveStuTestPractice",
                                    async: true,
                                    data: {
                                        "jsonStr": jsonStrs
                                    },
                                    success: function(msg) {
                                        loading1.hide();
                                        msg = JSON.parse(msg);
                                        if(msg.result == "success") {
                                            Alert1.content = "实验报告提交成功";
                                            Alert1.init();
                                            Alert1.show();
                                        }else{
                                            if(msg.failMsg!=undefined){
                                                if(msg.failMsg != ""){
                                                    Alert1.content = msg.failMsg;
                                                }else{
                                                    Alert1.content = "实验报告提交失败";
                                                }
                                                Alert1.init();
                                                Alert1.show();
                                            }else{
                                                Alert1.content = "实验报告提交失败";
                                                Alert1.init();
                                                Alert1.show();
                                            }
                                        }
                                    }
                                });
                            }else{
                                if(msg.failMsg!=undefined){
                                    if(msg.failMsg != ""){
                                        Alert1.content = msg.failMsg;
                                    }else{
                                        Alert1.content = "实验报告保存失败";
                                    }
                                    Alert1.init();
                                    Alert1.show();
                                }else{
                                    Alert1.content = "实验报告保存失败";
                                    Alert1.init();
                                    Alert1.show();
                                }
                            }
                        }
                    });


                };
                confirm1.show();

            }

        },
        noteChange:function () {
            // $("#if").load(function () {
            //     $("#if").contents().find("link").remove();
            //     $("#if").contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
            // });
        },
        getData: function(courseId,chapterNum,chapterId) {
            var self = this;
            var jsonStr = JSON.stringify({
                "chapterNum": chapterNum,
                "courseId":courseId
            });
            $.ajax({
                type: "post",
                url: "skipTestEnvirunmentList",
                async: true,
                data: {
                    "jsonStr": jsonStr
                },
                success: function(msg) {
                    msg = JSON.parse(msg);
                    if(msg.chapterMsg!=null){
                        if(msg.chapterMsg.testDocName!=undefined&&msg.chapterMsg.testDocName!=null&&msg.chapterMsg.testDocName!=""){
                            $labTextContent.attr("src", msg.url + msg.chapterMsg.testDocName);
                            self.noteChange();
                        }else{
                            $labTextContent.attr("src","pc/page/noResourceShow.html");
                        }
                        if(msg.taskMsg!=undefined && msg.taskMsg!= null&& msg.taskMsg!= ''){
                            $(".edit").html(unescape(msg.taskMsg));
                        }else {
                            var str = unescape(msg.chapterMsg.expreHtml);
                             $(".edit").html(unescape(str));
                        }
                        if(msg.testAssign != null && msg.testAssign != "" && msg.testAssign != undefined) {
                            $(".reportShow").height($(window).height()-120);
                            $(".reportShow").attr("src",msg.stuUrl+msg.chapterMsg.testfileName);
                            $(".downReportBtn").attr("href",msg.stuUrl+msg.chapterMsg.testfileName);
                            $(".title2").hide();
                            $(".title3").css("left","218px");
                            // 新增需求
                            $("#labScore").html(msg.testAssign.taskSoruce + '分');
                            $(".levelTop").css("width",msg.testAssign.taskSoruce+"%");
                            $("#ExperimentTextarea").html(msg.testAssign.lable)
                        }else{
                            $(".title3").hide();
                        }
                    }
                    // 返回上一页
                    $(".cancelBtn").off("click").click(function() {
                        confirm1.content = "确定退出实验环境吗？";
                        confirm1.success = function () {
                            $("#ifMain",parent.document).attr("style","");
                            var json = JSON.stringify({
                                "pageName":"myCourse",
                                "paramData":{
                                    "courseId":msg.chapterMsg.courseId
                                }
                            });
                            window.location.href = "skipPage?jsonStr="+json;
                        };
                        // window.location.href = "skipMain";
                        confirm1.init();
                        confirm1.show();
                    });

                    if(msg.chapterMsg.videoName != null && msg.chapterMsg.videoName != ""){
                        self.videoShow(msg.url + msg.chapterMsg.videoName);
                    }else{
                        self.videoShow(0);
                    }
                    if(msg.note != null){
                        if(msg.note.noteStr != undefined && msg.note.noteStr != null){
                            $edits.html(msg.note.noteStr);
                        }
                        if(msg.note.note_id != undefined && msg.note.note_id != null){
                            $saveNote.attr("note_id", msg.note.note_id);
                        }
                    }

                }
            });
            // 虚机资源获取
            var jsons = {"courseId":courseId,"chapterId":chapterId};
            $.ajax({
                type: "get",
                url: "desktop/query",
                data:jsons,
                async: true,
                success: function (msg) {
                    if(msg.code == "200"){
                        var str = '';
                        var str1 = '';
                        if(msg.data.cluster == true){
                            setTimeout(function () {
                                str += "<li data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点(当前)</li>";
                                str += "<li data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                str += "<li data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                $("#virtualBox").append("<iframe name='virMBoxes' data-value='1' data-containerid="+ msg.data.masterContainerId  +" class=\"virMBox\" src="+msg.data.masterDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");
                                $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.firstSlaveContainerId +" class=\"virMBox\" src="+msg.data.firstSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                $("#virtualBox").append("<iframe name='virMBoxes'  data-value='0' data-containerid="+ msg.data.secondSlaveContainerId +" class=\"virMBox\" src="+msg.data.secondSlaveDesktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;display: none;\"></iframe>");
                                // $(".configBox>ul").html(str);
                                str1 += "<li type='1' class='nav mainVir' data-value='1' data-url='"+ msg.data.masterDesktopUrl +"'  data-containerid="+ msg.data.masterContainerId +">主节点</li>";
                                str1 += "<li type='2' class='nav subVir' data-value='0' data-url='"+ msg.data.firstSlaveDesktopUrl +"'  data-containerid="+ msg.data.firstSlaveContainerId +">从节点1</li>";
                                str1 += "<li type='2' class='nav thVir' data-value='0' data-url='"+ msg.data.secondSlaveDesktopUrl +"'  data-containerid="+ msg.data.secondSlaveContainerId +">从节点2</li>";
                                $(".virAfter").after(str1);
                            },1000);

                        }else{
                            setTimeout(function () {
                                $(".configBtn").remove();
                                // str += "<li data-value='1' data-url='"+ msg.data.desktopUrl +"'  data-containerid="+ msg.data.containerId +">单节点(当前)</li>";
                                $("#virtualBox").append("<iframe  name='virMBoxes' data-value='1' data-containerid="+ msg.data.containerId +" class=\"virMBox\" src="+msg.data.desktopUrl +"  frameborder=\"0\" style=\"width: 100%;height: 100%;\"></iframe>");

                            },1000);
                        }
                        setTimeout(function () {
                            startWebSocket(courseId,chapterId);
                            self.somethingEvent(courseId,chapterId);
                            $(".mainVir").css({"background":'url(pc/images/ico_labMPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                            $(".mainVir").off("click").click(function () {
                                $(".nav").attr("style",'');
                                $(".nav").attr("data-value",'0');
                                $(this).css({"background":'url(pc/images/ico_labMPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                $(this).attr("data-value","1");
                                $(".virMBox").attr("data-value","0").hide();
                                $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                            });
                            $(".subVir").off("click").click(function () {
                                $(".nav").attr("style",'');
                                $(".nav").attr("data-value",'0');
                                $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                $(this).attr("data-value","1");
                                $(".virMBox").attr("data-value","0").hide();
                                $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                            });
                            $(".thVir").off("click").click(function () {
                                $(".nav").attr("style",'');
                                $(".nav").attr("data-value",'0');
                                $(this).css({"background":'url(pc/images/ico_labSPC2.png) no-repeat left 6px center',"color":'#0fcc8c'});
                                $(this).attr("data-value","1");
                                $(".virMBox").attr("data-value","0").hide();
                                $(".virMBox[data-containerid="+ $(this).attr("data-containerid") +"]").attr("data-value","1").show()
                            });
                        },1000);

                        // // 获取sftp地址和端口
                        // $.ajax({
                        //     type: "get",
                        //     url: "desktop/ftp",
                        //     data: {"containerId":Number($(".virMBox[data-value=1]").attr("data-containerid"))},
                        //     async: true,
                        //     dataType: 'json',
                        //     contentType: 'application/json',
                        //     success: function (msg) {
                        //         if (msg.code == "200") {
                        //             var arr = msg.data.ftp.split(":");
                        //             $(".blueHtml").html(arr[0]);
                        //             $(".blueHtml2").html(arr[1]);
                        //         }else{
                        //             Alert1.content = msg.message;
                        //             Alert1.init();
                        //             Alert1.show();
                        //             return false;
                        //         }
                        //     }
                        // });
                        // 实验环境Loading
                        setTimeout(function () {
                            $("#virtualBox").append("<div style='width:100%;height:100%;background:#666666;position:absolute;left:0;top:0;' class='loadingBg'><img style='transform:scale(0.7);position:absolute;left:50%;top:50%;margin-left:-200px;margin-top:-75px;' class='loadings' src='pc/images/labLoadings.gif'></div>");
                            $(".virMBox[data-value=1]").load(function () {
                                $(".loadingBg").remove();
                            });
                        },1000);

                        self.screenShoot();
                        $(".shareDeskCloseBtn").off("click").click(function () {
                            var serverid = $(".virMBox[data-value=1]").attr("data-containerid");
                            if(serverid == undefined){
                                Alert1.content = "当前无法关闭分享";
                                Alert1.init();
                                Alert1.show();
                            }else{
                                var json = {"containerId":serverid};
                                $.ajax({
                                    type: "get",
                                    url: "desktop/unshare",
                                    data:json,
                                    async: true,
                                    success: function(msg) {
                                        if(msg.code == "200"){
                                            Alert1.content = "关闭分享成功";
                                            Alert1.success = function () {
                                            };
                                            Alert1.init();
                                            Alert1.show();
                                        }else{
                                            Alert1.content = msg.message;
                                            Alert1.init();
                                            Alert1.show();
                                        }
                                    }
                                });
                            }

                        });
                    }else{
                        Alert1.content = msg.message;
                        Alert1.init();
                        Alert1.show();
                        $(".navSideBar").remove();
                        $("#virtualBox").css("background","url(pc/images/bg_labNoneVir.png) no-repeat center center");
                    }
                }
            });
        },
        titleTap: function() {
            var self = this;
            //			实验文档报告评价切换
            $(".title>div").off("click").click(function() {
                $(this).addClass("titleChoose").siblings("div").removeClass("titleChoose");
                $(".contentSection").children("div").hide().eq($(this).index()).show();
            });
        },
        screenShoot: function() {
            var self = this;
            //			截屏
            $(".subBtn").off("click").click(function() {
                var vir = document.getElementsByClassName('virMBox');
                for(var i=0;i<vir.length;i++){
                    if(vir[i].getAttribute("data-value") == 1){
                        var sImg = convertCanvasToImage(vir[i].contentWindow.document.getElementsByTagName('canvas')[0]);
                        // $(".edit").append(sImg);
                        $(self.report).append(sImg);
                    }
                }
            });
            $(".subBtns").off("click").click(function() {
                var vir = document.getElementsByClassName('virMBox');
                for(var i=0;i<vir.length;i++){
                    if(vir[i].getAttribute("data-value") == 1){
                        var sImg = convertCanvasToImage(vir[i].contentWindow.document.getElementsByTagName('canvas')[0]);
                        // $(".edits").append(sImg);
                        $(self.note).append(sImg);
                    }
                }
            });
            // var screenCanvas = $(".virMBox").contents().find("#noVNC_canvas");
            // if(screenCanvas != undefined){
            //     var timer = setInterval(function() {
            //         screenCanvas.height($(window).height() - 38 + "px");
            //         screenCanvas.width((1024 / 768) * ($(window).height() - 38) + "px");
            //     }, 50);
            // }
        },
        layout: function() {
            $virtualBox.height($(window).height() - 38);
            $(".contentSection").height($(window).height() - 38);
            $(".navSideBar").height($(window).height() - 38);
            $(window).resize(function() {
                $virtualBox.height($(window).height() - 38);
                $(".contentSection").height($(window).height() - 38);
                $(".navSideBar").height($(window).height() - 38);
            });
        }
    };
    lab.init();
// startWebSocket();
//		var star = new startWebSocket();
//		star.onmessage();
    //桌面共享
    function startWebSocket(courseid,chapterid) {
        var shareServeId;
        var confirm2 = new Confirm();
        var shareStuorteaId;
        // var path = result.server_address.substring(7)+result.project_name;
        var path = "";
        $.ajax({
            type:"get",
            url: "common/project",
            async: true,
            success: function(msg) {
                if(msg.code == 200){
                    path = msg.data;
                    var wsuri = "ws://" + path + "webSocket/desktop/"+courseid+"/" + chapterid;
                    var ws;
                    if ('WebSocket' in window) {
                        ws = new WebSocket(wsuri);
                    } else if ('MozWebSocket' in window) {
                        ws = new MozWebSocket(wsuri);
                    } else {
                        Alert1.content = "当前浏览器不支持websocket，不能进行桌面共享";
                        Alert1.init();
                        Alert1.show();
                    }

                    var myDate = new Date();
                    ws.onopen = function () {

                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onopen");
                    };
                    ws.onmessage = function (evt) {
                        var data = JSON.parse(evt.data);
                        if (data.type == 1) {
                            confirm2.content = "是否接受来自" + data.username + "的共享桌面";
                            confirm2.success = function () {
                                shareServeId = data.containerId;
                                shareStuorteaId = data.stuorteaId;
                                var url = data.desktopUrl;
                                $(".getShareWin").show();
                                $(".getShareWin").html("来自" + data.username + "的共享桌面");
                                $(".getShareWin").off("click").click(function () {
                                    $(".shareWinBox").show();
                                    if (result.roleId == 2) {
                                        $(".mengban").css("height", "0px");
                                    } else {
                                        $(".mengban").css("height", "100%");
                                    }

                                });
                                if (data.controllable == false) {
                                    if (result.roleId == 2) {
                                        $(".mengban").css({"display": "block", "height": "0px"});
                                    } else {
                                        $(".mengban").css({"display": "block", "height": "100%"});
                                    }

                                } else {
                                    $(".mengban").css("display", "");
                                }
                                $(".shareWinBox").css("display", "block");
                                $("#shareWindow").attr("src", url);
                                $("#shareWindow").css({"width": "100%", "height": $(window).height() - 50 + "px"});
                                $(".sharevirTitle").html("来自" + data.username + "的共享桌面");
                                $(".sharevirTitle").append("<span class=\"close4\"></span><img src=\"pc/images/ico_shareClose.png\" class=\"shareCloseBtn\" title=\"关闭\" alt=\"关闭\" />");

                                $(".close4").off("click").click(function () {
                                    $(".shareWinBox").hide();
                                    $(".mengban").css("height", "0");
                                });
                                $(".shareCloseBtn").off("click").click(function () {
                                    confirm2.content = "确定关闭接收的共享桌面吗？";
                                    confirm2.success = function () {
                                        shareStuorteaId = "";
                                        shareServeId = "";
                                        $(".getShareWin").hide();
                                        $(".shareWinBox").hide();
                                        $("#shareWindow").attr("src", "");
                                        $(".mengban").css("height", "0");
                                    };
                                    confirm2.init();
                                    confirm2.show();
                                });

                            };
                            confirm2.init();
                            confirm2.show();
                        } else if (data.type == 2) {
                            if (shareServeId == data.containerId && shareStuorteaId == data.stuorteaId) {
                                shareStuorteaId = "";
                                shareServeId = "";
                                Alert1.content = "桌面共享已关闭";
                                Alert1.success = function () {
                                    $(".getShareWin").hide();
                                    $(".shareWinBox").hide();
                                    $("#shareWindow").attr("src", "");
                                    $(".mengban").css("height", "0");
                                };
                                Alert1.init();
                                Alert1.show();
                            }
                        } else {
                            if (shareStuorteaId == data.stuorteaId) {
                                shareStuorteaId = "";
                                Alert1.content = "桌面共享已关闭";
                                Alert1.success = function () {
                                    $(".getShareWin").hide();
                                    $(".shareWinBox").hide();
                                    $("#shareWindow").attr("src", "");
                                    $(".mengban").css("height", "0");
                                };
                                Alert1.init();
                                Alert1.show();
                            }
                        }
                    };
                    ws.onclose = function (evt) {
                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onclose");
                    };
                    ws.onerror = function () {
                        console.log(myDate.getDate() + ":" + myDate.getHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() + ":" + myDate.getMilliseconds() + "--onerror");
                    };
                }
            }
        });

    }
});
